/**
 * 
 */
package helper;

import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import database.Database;

/**
 * @author Ken
 *
 */
public class SaveLoadDB {
	public static String SaveDB(Database database){
		try{
			XMLEncoder encoder = new XMLEncoder(new BufferedOutputStream(new FileOutputStream("data/" + database.toString() + ".xml")));
			encoder.writeObject(database);
			encoder.close();
			return "Success";
		}
		catch (Exception e){
			return e.toString();
		}		
	}
	public static Database[] LoadDB(String result){
		try {
			File dir = new File(".");
			String directory = dir.getCanonicalPath();
			directory += "/data/";
			File folder = new File(directory);
			File[] files = folder.listFiles();
			Database[] databases = new Database[files.length];
			for (int i = 0; i < databases.length; i++) {						
				XMLDecoder decoder = new XMLDecoder(new BufferedInputStream(new FileInputStream(files[i])));
				databases[i] = (Database)decoder.readObject();
				decoder.close();				
			}					
			return databases;
		}
		catch (Exception e){
			result = e.toString();
			return null;
		}
	}
}
